package me.zhengjie.config.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName WechatUtil
 * @Description 微信工具类
 */
public class WechatUtil {
	
	/**
	 * 将微信推送来的消息(XML)转成Map
	 * @param req
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,String> reqMsgToMap(HttpServletRequest req) throws IOException {
		String xml = reqToxml(req);
		try {
			Map<String,String> maps = new HashMap<String, String>();
			Document document = DocumentHelper.parseText(xml);
			Element root = document.getRootElement();
			List<Element> eles = root.elements();
			for(Element e:eles) {
				maps.put(e.getName(), e.getTextTrim());
			}
			return maps;
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 读取微信推送的消息
	 * @param req
	 * @return
	 * @throws IOException
	 */
	public static String reqToxml(HttpServletRequest req) throws IOException {
		BufferedReader br = null;
		br = new BufferedReader(new InputStreamReader(req.getInputStream()));
		String str = null;
		StringBuffer sb = new StringBuffer();
		while((str=br.readLine())!=null) {
			sb.append(str);
		}
		return sb.toString();
	}

	/**
     * 过滤昵称特殊表情
     */
    public static String filterNickName(String name) {
        if(name==null){
            return null;
        }
        if("".equals(name.trim())){
            return "";
        }
        Pattern patter = Pattern.compile("[a-zA-Z0-9\u4e00-\u9fa5]");
        Matcher match = patter.matcher(name);
        StringBuffer buffer = new StringBuffer();
        while (match.find()) {
            buffer.append(match.group());
        }
        return buffer.toString();
    }
	
}
